﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GCDF.Common.Report;
using GCDF.PL.Common.Report;
using Workflow.Common;
using Workflow.Common.Tools;
using Workflow.Dto;
using Workflow.IService;
using Workflow.Model;
using Workflow.Model.Enum;
using Workflow.Resource;
using Workflow.Web.Common;
using Workflow.Common.ExcelHelp;

namespace Workflow.Web.Controllers
{
	[Localization]
	[UserAuthorize]
	public class GPEEMController : Controller
	{
		public ICaseEEMService CaseEEMService { get; set; }
		public IWorkStatusService WorkStatusService { get; set; }
		public IUserManager UserManager { get; set; }
		public IDistributeService DistributeService { get; set; }
		public IReceivedService ReceivedService { get; set; }
		public IPaymentService PaymentService { get; set; }
		public ICaseReasonService CaseReasonService { get; set; }
		//
		// GET: /GPEEM/

		public ActionResult Inquiry()
		{
			
			var users = UserManager.GetUserForRole((int)EnumRole.GPEEMPA);
			var users2 = UserManager.GetUserForRole((int)EnumRole.GPAHEEMPA);
			List<User> data =new List<User>();

			data.AddRange(users);
			data.AddRange(users2);
			//var users = UserManager.GetUserForRole((int)EnumRole.GPEEMPA);
			string role = Session[ConfigReader.AuthorizeSessionUserRoleCode].ToString();
			ViewData["RoleCode"] = int.Parse(role);
			ViewData["UserList"] = data;
			return View();
		}
		public ActionResult MyTask()
		{
			string role = Session[ConfigReader.AuthorizeSessionUserRoleCode].ToString();
			ViewData["RoleCode"] = int.Parse(role);

			return View();
		}
		public ActionResult CaseMonitor()
		{
			return View("RecievBox");
		}
		public ActionResult PAMonitor()
		{
			return View();
		}
		public ActionResult GetData()
		{
			string s = Request["page"] ?? "1";
			string r = Request["rows"];
			string sortfield = Request["sort"];
			string order = Request["order"];
			if (sortfield == null)
				sortfield = "InvoiceNo";
			if (r == null)
				r = "5";
			long count;
			string orderby = order;
			string folderLevelA = Request["FolderLevelA"];
			string folderLevelB = Request["FolderLevelB"];
			string workStatus = Request["WorkStatus"];
			string fileName = Request["FileName"];
			string invoiceNo = Request["InvoiceNo"];
			string receiveDateFrom = Request["ReceiveDateFrom"];
			string receiveDateTo = Request["ReceiveDateTo"];
			string checkType = Request["CheckType"];
			string operatorId = Request["OperatorID"];
			string queryStatusOperatorId = Request["StatusOperatorID"];
			string statusDateFrom = Request["StatusDateFrom"];
			string statusDateTo = Request["StatusDateTo"];
			string payment = Request["Payment"];
			string reason = Request["Reason"];

			CaseQueryDto caseQueryDto = new CaseQueryDto();
			int d = (int)EnumFolderClass.EEM;
			caseQueryDto.ProcessType = d.ToString();
			caseQueryDto.FolderLevelA = folderLevelA;
			caseQueryDto.FolderLevelB = folderLevelB;
			caseQueryDto.WorkStatus = workStatus;
			caseQueryDto.FileName = fileName;
			caseQueryDto.InvoiceNo = invoiceNo;
			caseQueryDto.ReceiveDateFrom = receiveDateFrom;
			caseQueryDto.ReceiveDateTo = receiveDateTo;
			caseQueryDto.CheckType = checkType;
			caseQueryDto.OperatorId = operatorId;
			caseQueryDto.StatusOperatorID = queryStatusOperatorId;
			caseQueryDto.StatusDateFrom = statusDateFrom;
			caseQueryDto.StatusDateTo = statusDateTo;
			caseQueryDto.Payment = payment;
			caseQueryDto.CommentCode = reason;

			// caseQueryDto.OperatorId = operatorid;
			//IList<Case> cases = CaseService.GetAllCaseByPage(out count, int.Parse(s), int.Parse(r), caseQueryDto, orderby, sortfield);
			IList<CaseEEM> cases = CaseEEMService.GetAllCaseByPage(out count, int.Parse(s), int.Parse(r), caseQueryDto, orderby, sortfield);
			IList<CaseViewDto> caseViewDtos = new List<CaseViewDto>();
			foreach (var c in cases)
			{
				caseViewDtos.Add(new CaseViewDto(c.CaseNo.ToString(),
													c.FileName,
													c.CaseMapPropertyEEM == null ? null : c.CaseMapPropertyEEM.Payment == null ? null : c.CaseMapPropertyEEM.Payment.PaymentName,//c.ProcessType.FolderName,
													c.FolderLevelA.FolderName,
													c.FolderLevelB == null ? null : c.FolderLevelB.FolderName,
													c.CheckType == null ? null : c.CheckType.FolderName,
													c.InvoiceNo,
													c.WorkStatus.WorkStatusNameEEM,
													c.Operator == null ? null : c.Operator.UserName,
													c.ReceiveDate == null ? null : ((DateTime)c.ReceiveDate).ToString("yyyy/MM/dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo),
												   c.StatusDate == null ? null : ((DateTime)c.StatusDate).ToString("yyyy/MM/dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo),
												   c.StatusOperator == null ? null : c.StatusOperator.UserName,
												   c.BatchNo.Substring(9,4),
													 c.CommentCode == null ? null : c.CommentCode.JpReason));
			}
			JsonModel<CaseViewDto> JsonModel = new JsonModel<CaseViewDto>();
			JsonModel.total = count.ToString();
			JsonModel.rows = caseViewDtos;
			return this.Json(JsonModel, JsonRequestBehavior.AllowGet);
		}
		[HttpPost]
		public ActionResult GetMyTaskData()
		{
			string s = Request["page"] ?? "1";
			string r = Request["rows"];
			string sortfield = Request["sort"];
			string order = Request["order"];
			if (sortfield == null)
				sortfield = "InvoiceNo";
			if (r == null)
				r = "5";
			long count;
			string orderby = order;

			string workStatus = Request["WorkStatus"];
			string invoiceNo = Request["InvoiceNo"];
			string receiveDateFrom = Request["ReceiveDateFrom"];
			string receiveDateTo = Request["ReceiveDateTo"];

			string fileName = Request["FileName"];
			//string operatorid = Request["OperatorID"];

			CaseQueryDto caseQueryDto = new CaseQueryDto();
			int d = (int)EnumFolderClass.EEM;
			caseQueryDto.ProcessType = d.ToString();

			caseQueryDto.WorkStatus = workStatus;
			caseQueryDto.InvoiceNo = invoiceNo;
			caseQueryDto.ReceiveDateFrom = receiveDateFrom;
			caseQueryDto.ReceiveDateTo = receiveDateTo;

			caseQueryDto.FileName = fileName;

			//PA only load his data
			int role = int.Parse(Session[ConfigReader.AuthorizeSessionUserRoleCode].ToString());
			if (role == (int)EnumRole.GPPTPPA || role == (int)EnumRole.GPEEMPA || role == (int)EnumRole.GPAHEEMPA)
			{
				caseQueryDto.OperatorId = Session[ConfigReader.AuthorizeSessionUserID].ToString();
			}
			
			// caseQueryDto.OperatorId = operatorid;
			//IList<Case> cases = CaseService.GetCaseByUser(out count, int.Parse(s), int.Parse(r), caseQueryDto, orderby, sortfield);
			IList<CaseEEM> cases = CaseEEMService.GetCaseByUser(out count, int.Parse(s), int.Parse(r), caseQueryDto, orderby, sortfield);
			IList<CaseViewDto> caseViewDtos = new List<CaseViewDto>();
			foreach (var c in cases)
			{
				caseViewDtos.Add(new CaseViewDto(c.CaseNo.ToString(),
												 c.FileName,
												 "EEM",//c.ProcessType.FolderName,
												 c.FolderLevelA.FolderName,
												 c.FolderLevelB.FolderName,
												 c.CheckType.FolderName,
												 c.InvoiceNo,
												 c.WorkStatus.WorkStatusNameEEM,
												 c.Operator == null ? null : c.Operator.UserName,
												 c.ReceiveDate == null ? null : ((DateTime)c.ReceiveDate).ToString("yyyy/MM/dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo),
												 c.StatusDate == null ? null : ((DateTime)c.StatusDate).ToString("yyyy/MM/dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo),
												 c.StatusOperator == null ? null : c.StatusOperator.UserName,
												   c.BatchNo.Substring(9, 4),
													c.StatusComment == null ? "" : c.StatusComment.ToString().Replace("\r\n", ""),
													c.WorkStatus.WorkStatusCode));


			}
			JsonModel<CaseViewDto> JsonModel = new JsonModel<CaseViewDto>();
			JsonModel.total = count.ToString();
			JsonModel.rows = caseViewDtos;
			return this.Json(JsonModel, JsonRequestBehavior.AllowGet);
		}

		public ActionResult GetWorkStutes(string level)
		{
			var date = WorkStatusService.GetAllWorkStatus();
			date.Insert(0, new WorkStatus() { WorkStatusCode = "", WorkStatusNamePTP = Global.pleaseSelect, WorkStatusName = Global.pleaseSelect, WorkStatusNameEEM = Global.pleaseSelect });
			if (level == "PL")
			{
				date = (from model in date
						where model.WorkStatusCode == ((int)EnumWorkStatus.Reject).ToString() ||
							  model.WorkStatusCode == ((int)EnumWorkStatus.Closed).ToString()
						select model).ToList();
			}
			else if (level == "PA")
			{
				date = (from model in date
						where model.WorkStatusCode == ((int)EnumWorkStatus.Distributed).ToString() ||
							  model.WorkStatusCode == ((int)EnumWorkStatus.WaitForCheck).ToString() ||
							  model.WorkStatusCode == ((int)EnumWorkStatus.Pending_QA).ToString() ||
							  model.WorkStatusCode == ""
						select model).ToList();
			}
			return Json(date, "text/plain", JsonRequestBehavior.AllowGet);

		}
		public ActionResult GetPayments()
		{
			int d = (int)EnumFolderClass.EEM;
			var date = PaymentService.GetPaymentList(d.ToString());
			date.Insert(0, new Payment() { PaymentId = "", PaymentName = Global.pleaseSelect });
			return Json(date, "text/plain", JsonRequestBehavior.AllowGet);

		}

		public ActionResult GetCaseReasonList()
		{
			int d = (int)EnumFolderClass.EEM;
			var date = CaseReasonService.GetCaseReasonByType(d.ToString());
			date.Insert(0, new CaseReason() { Id = "", JpReason = Global.pleaseSelect });
			return Json(date, "text/plain", JsonRequestBehavior.AllowGet);
		}
		public ActionResult GetFolderLevel(string id)
		{
			string pm = id;
			//string pm = Request["id"];
			//var date = CaseService.GetFolderClass(pm);
			var date = CaseEEMService.GetFolderClass(pm);

			date.Insert(0, new FolerClass() { FolderCode = "", FolderName = Global.pleaseSelect });
			return Json(date, "text/plain", JsonRequestBehavior.AllowGet);
		}

		/// <summary>
		/// 指定CASE分配给指定人
		/// </summary>
		/// <returns></returns>
		public ActionResult DistributeCase()
		{
			try
			{
				var caseNos = Request["caseNos"];
				var userID = Request["user"];
				var user = UserManager.GetUser(Int64.Parse(userID));
				var statusOperatorID = Session[ConfigReader.AuthorizeSessionUserID].ToString();
				var statusOperator = UserManager.GetUser(Int64.Parse(statusOperatorID));

				var failCase = DistributeService.UpdateEEMCaseForDistribute(caseNos.Split(','), user, statusOperator);

				if (failCase.Count >0)
				{
					var failCases =string.Join(",",failCase);
					var msg = String.Format(Global.DistributeFailCaseMsg, failCases);
					return Json(new { Success = true, Message = msg }, "text/html", JsonRequestBehavior.AllowGet);
	
				}
				return Json(new { Success = true, Message = Global.distributeSuccess }, "text/html", JsonRequestBehavior.AllowGet);
			}
			catch (Exception ec)
			{
				return Json(new { Success = true, Message = Global.distributefail }, "text/html", JsonRequestBehavior.AllowGet);

			}
		}
		/// <summary>
		/// 根据条件分配给指定人
		/// </summary>
		/// <returns></returns>
		public ActionResult DistributeCaseAll()
		{
			try
			{
				string folderLevelA = Request["FolderLevelA"];

				string workStatus = Request["WorkStatus"];
				string fileName = Request["FileName"];
				string invoiceNo = Request["InvoiceNo"];
				string receiveDateFrom = Request["ReceiveDateFrom"];
				string receiveDateTo = Request["ReceiveDateTo"];

				string operatorId = Request["OperatorID"];
				string folderLevelB = Request["FolderLevelB"];
				string checkType = Request["CheckType"];
				string queryStatusOperatorId = Request["StatusOperatorID"];
				string statusDateFrom = Request["StatusDateFrom"];
				string statusDateTo = Request["StatusDateTo"];
				string payment = Request["Payment"];
				string reason = Request["Reason"];

				//string operatorid = Request["OperatorID"];

				CaseQueryDto caseQueryDto = new CaseQueryDto();
				int d = (int)EnumFolderClass.EEM;
				caseQueryDto.ProcessType = d.ToString();
				caseQueryDto.FolderLevelA = folderLevelA;
				caseQueryDto.FolderLevelB = folderLevelB;
				caseQueryDto.CheckType = checkType;
				caseQueryDto.WorkStatus = workStatus;
				caseQueryDto.FileName = fileName;
				caseQueryDto.InvoiceNo = invoiceNo;
				caseQueryDto.ReceiveDateFrom = receiveDateFrom;
				caseQueryDto.ReceiveDateTo = receiveDateTo;
				caseQueryDto.OperatorId = operatorId;
				caseQueryDto.StatusOperatorID = queryStatusOperatorId;
				caseQueryDto.StatusDateFrom = statusDateFrom;
				caseQueryDto.StatusDateTo = statusDateTo;
				caseQueryDto.Payment = payment;
				caseQueryDto.CommentCode = reason;

				//IList<Case> cases = CaseService.GetAllCase(caseQueryDto);
				IList<CaseEEM> cases = CaseEEMService.GetAllCase(caseQueryDto);


				var userID = Request["user"];
				var user = UserManager.GetUser(Int64.Parse(userID));
				var statusOperatorID = Session[ConfigReader.AuthorizeSessionUserID].ToString();
				var statusOperator = UserManager.GetUser(Int64.Parse(statusOperatorID));

				var failCase = DistributeService.UpdateEEMCaseForDistribute(cases, user, statusOperator);

				if (failCase.Count > 0)
				{
					var failCases = string.Join(",", failCase);
					var msg = String.Format(Global.DistributeFailCaseMsg, failCases);
					return Json(new { Success = true, Message = msg }, "text/html", JsonRequestBehavior.AllowGet);

				}
				return Json(new { Success = true, Message = Global.distributeSuccess }, "text/html", JsonRequestBehavior.AllowGet);
			}
			catch (Exception ex)
			{
				return Json(new { Success = true, Message = Global.distributefail }, "text/html", JsonRequestBehavior.AllowGet);

			}

		}

		/// <summary>
		/// 个人领取指定CASE
		/// </summary>
		/// <returns></returns>
		public ActionResult PickUpCase()
		{
			try
			{
				var caseNos = Request["caseNos"];
				var userid = Session[ConfigReader.AuthorizeSessionUserID];
				var user = UserManager.GetUser(Int64.Parse(userid.ToString()));

				var failCase = DistributeService.UpdateEEMCaseForPickUp(caseNos.Split(','), user, user);
				if (failCase.Count > 0)
				{
					var failCases = string.Join(",", failCase);
					var msg = String.Format(Global.PickUpFailCaseMsg, failCases);
					return Json(new { Success = true, Message = msg }, "text/html", JsonRequestBehavior.AllowGet);

				}
				return Json(new { Success = true, Message = Global.pickupSuccess }, "text/html", JsonRequestBehavior.AllowGet);

			}
			catch (Exception)
			{

				return Json(new { Success = true, Message = Global.pickupfail }, "text/html", JsonRequestBehavior.AllowGet);

			}
		}

		public ActionResult PickUpCaseAll()
		{
			try
			{
				string folderLevelA = Request["FolderLevelA"];

				string workStatus = Request["WorkStatus"];
				string fileName = Request["FileName"];
				string invoiceNo = Request["InvoiceNo"];
				string receiveDateFrom = Request["ReceiveDateFrom"];
				string receiveDateTo = Request["ReceiveDateTo"];
				string operatorId = Request["OperatorID"];
				string folderLevelB = Request["FolderLevelB"];
				string checkType = Request["CheckType"];
				string queryStatusOperatorId = Request["StatusOperatorID"];
				string statusDateFrom = Request["StatusDateFrom"];
				string statusDateTo = Request["StatusDateTo"];
				string payment = Request["Payment"];
				string reason = Request["Reason"];


				CaseQueryDto caseQueryDto = new CaseQueryDto();
				int d = (int)EnumFolderClass.EEM;
				caseQueryDto.ProcessType = d.ToString();
				caseQueryDto.FolderLevelA = folderLevelA;
				caseQueryDto.FolderLevelB = folderLevelB;
				caseQueryDto.CheckType = checkType;
				caseQueryDto.WorkStatus = workStatus;
				caseQueryDto.FileName = fileName;
				caseQueryDto.InvoiceNo = invoiceNo;
				caseQueryDto.ReceiveDateFrom = receiveDateFrom;
				caseQueryDto.ReceiveDateTo = receiveDateTo;
				caseQueryDto.OperatorId = operatorId;
				caseQueryDto.StatusOperatorID = queryStatusOperatorId;
				caseQueryDto.StatusDateFrom = statusDateFrom;
				caseQueryDto.StatusDateTo = statusDateTo;
				caseQueryDto.Payment = payment;
				caseQueryDto.CommentCode = reason;

				//IList<Case> cases = CaseService.GetAllCase(caseQueryDto);
				IList<CaseEEM> cases = CaseEEMService.GetAllCase(caseQueryDto);

				var userid = Session[ConfigReader.AuthorizeSessionUserID];
				var user = UserManager.GetUser(Int64.Parse(userid.ToString()));
				var failCase = DistributeService.UpdateEEMCaseForPickUp(cases, user, user);
				if (failCase.Count > 0)
				{
					var failCases = string.Join(",", failCase);
					var msg = String.Format(Global.PickUpFailCaseMsg, failCases);
					return Json(new { Success = true, Message = msg }, "text/html", JsonRequestBehavior.AllowGet);

				}
				return Json(new { Success = true, Message = Global.pickupSuccess }, "text/html", JsonRequestBehavior.AllowGet);
			}
			catch (Exception)
			{
				return Json(new { Success = true, Message = Global.pickupfail }, "text/html", JsonRequestBehavior.AllowGet);
			}

		}

		public ActionResult GetUserList()
		{
			var users = UserManager.GetUserForRole((int)EnumRole.GPEEMPA);
			var users2 = UserManager.GetUserForRole((int)EnumRole.GPAHEEMPA);
			var data = users.Select(x => new
			{
				UserID = x.UserID.ToString(),
				x.UserName
			}).ToList();
			var data2 = users2.Select(x => new
			{
				UserID = x.UserID.ToString(),
				x.UserName
			}).ToList();

			data.AddRange(data2);

			data.Insert(0, new { UserID = "", UserName = Global.pleaseSelect });
			return Json(data, "text/plain", JsonRequestBehavior.AllowGet);
		}

		/// <summary>
		/// EEM受付
		/// </summary>
		/// <returns></returns>
		public ActionResult EEMReceived()
		{
			try
			{
				//if (ImpersonateLogon.impersonateValidUser(ConfigurationManager.AppSettings["ImpersonateUser"],
				//                                     ConfigurationManager.AppSettings["ImpersonateDomain"],
				//                                     ConfigurationManager.AppSettings["ImpersonatePassword"]))
				//{


				string submitDate;

				submitDate = ToolsHelper.GetTimeZoneNow().ToString("yyyyMMdd");

				var data = ReceivedService.UpdateEEMReceivedCaseForFolder(submitDate);

				//    ImpersonateLogon.undoImpersonation();
				//}
				//else
				//{
				//    throw new Exception("Impersonate Logon Error!");
				//}


				return Json(new {Success = true, Message = Global.ReceivedSuccess, ErrorData = data}, "text/html",
				            JsonRequestBehavior.AllowGet);
			}
			catch (Exception)
			{

				return Json(new { Success = false, Message = Global.ReceivedFail }, "text/html", JsonRequestBehavior.AllowGet);

			}
		}

		public ActionResult GetRecievBox()
		{

			var workStatus = Request["WorkStatus"];
			var receiveDate = Request["ReceiveDate"];
			var checkType = Request["CheckType"];

			CaseMonitorQueryDto caseMonitorQueryDto = new CaseMonitorQueryDto();
			caseMonitorQueryDto.WorkStatus = workStatus;
			caseMonitorQueryDto.ReceiveDate = receiveDate;
			caseMonitorQueryDto.CheckType = checkType;

			var data = CaseEEMService.GetCaseMonitor(caseMonitorQueryDto);
			var totalf7 = data.Sum(x => x.f7);
			var totalf8 = data.Sum(x => x.f8);
			var totalf9 = data.Sum(x => x.f9);
			var total5 = data.Sum(x => x.total5);
			var totalf10 = data.Sum(x => x.f10);
			var totalf11 = data.Sum(x => x.f11);
			var totalf12 = data.Sum(x => x.f12);
			var totalf13 = data.Sum(x => x.f13);
			var totalf14 = data.Sum(x => x.f14);
			var totalf15 = data.Sum(x => x.f15);
			var totalf16 = data.Sum(x => x.f16);
			var totalf6 = data.Sum(x => x.total6);
			var allTotal = data.Sum(x => x.totlePage);
			data = data.OrderBy(x => x.batch).ToList();

			//var totalz3 = data.Sum(x => x.z3);
			//var totalAll = data.Sum(x => x.total);
			EEMCaseMonitorDto caseMonitorDto = new EEMCaseMonitorDto();
			caseMonitorDto.id = "1";
			caseMonitorDto.region = string.IsNullOrEmpty(receiveDate) ? ToolsHelper.GetTimeZoneNow().ToString("yyyy/MM/dd") : receiveDate; /////////当前选择时间
			caseMonitorDto.f7 = totalf7;
			caseMonitorDto.f8 = totalf8;
			caseMonitorDto.f9 = totalf9;
			caseMonitorDto.total5 = total5;
			caseMonitorDto.f10 = totalf10;
			caseMonitorDto.f11 = totalf11;
			caseMonitorDto.f12 = totalf12;
			caseMonitorDto.f13 = totalf13;
			caseMonitorDto.f14 = totalf14;
			caseMonitorDto.f15 = totalf15;
			caseMonitorDto.f16 = totalf16;
			caseMonitorDto.total6 = totalf6;
			caseMonitorDto.totlePage = allTotal;
			data.Insert(0, caseMonitorDto);
			JsonModel<EEMCaseMonitorDto> JsonModel = new JsonModel<EEMCaseMonitorDto>();
			JsonModel.total = "4";
			JsonModel.rows = data;
			return this.Json(JsonModel, JsonRequestBehavior.AllowGet);

		}

		public ActionResult GetPAMonitor()
		{
			var receiveDate = Request["ReceiveDate"];
			PAMonitorQueryDto paMonitorQueryDto = new PAMonitorQueryDto();
			paMonitorQueryDto.ReceiveDate = receiveDate;

			var datas = CaseEEMService.GetPAMonitor(paMonitorQueryDto);
			var users = (from data in datas
			             select data.UserID).Distinct().ToList();
			List<EEMPAMonitorDto> show = new List<EEMPAMonitorDto>();
			foreach (var user in users)
			{
				var user1 = user;
				var totalf7 = datas.Where(x => x.UserID == user1).Sum(x => x.f7);
				var totalf8 = datas.Where(x => x.UserID == user1).Sum(x => x.f8);
				var totalf9 = datas.Where(x => x.UserID == user1).Sum(x => x.f9);
				var total5 = datas.Where(x => x.UserID == user1).Sum(x => x.total5);
				var totalf10 = datas.Where(x => x.UserID == user1).Sum(x => x.f10);
				var totalf11 = datas.Where(x => x.UserID == user1).Sum(x => x.f11);
				var totalf12 = datas.Where(x => x.UserID == user1).Sum(x => x.f12);
				var totalf13 = datas.Where(x => x.UserID == user1).Sum(x => x.f13);
				var totalf14 = datas.Where(x => x.UserID == user1).Sum(x => x.f14);
				var totalf15 = datas.Where(x => x.UserID == user1).Sum(x => x.f15);
				var totalf16 = datas.Where(x => x.UserID == user1).Sum(x => x.f16);
				var total6 = datas.Where(x => x.UserID == user1).Sum(x => x.total6);
				var totlePage = datas.Where(x => x.UserID == user1).Sum(x => x.totlePage);

				EEMPAMonitorDto eempaMonitorDto = new EEMPAMonitorDto();

				eempaMonitorDto.id = user.ToString();
				eempaMonitorDto.region = datas.Where(x => x.UserID == user1).First().UserName;
				eempaMonitorDto.f7 = totalf7;
				eempaMonitorDto.f8 = totalf8;
				eempaMonitorDto.f9 = totalf9;
				eempaMonitorDto.total5 = total5;
				eempaMonitorDto.f10 = totalf10;
				eempaMonitorDto.f11 = totalf11;
				eempaMonitorDto.f12 = totalf12;
				eempaMonitorDto.f13 = totalf13;
				eempaMonitorDto.f14 = totalf14;
				eempaMonitorDto.f15 = totalf15;
				eempaMonitorDto.f16 = totalf16;
				eempaMonitorDto.total6 = total6;
				eempaMonitorDto.totlePage = totlePage;

				show.Add(eempaMonitorDto);

				show.AddRange(datas.Where(x => x.UserID == user1));
			}

			JsonModel<EEMPAMonitorDto> JsonModel = new JsonModel<EEMPAMonitorDto>();
			JsonModel.total = show.Count().ToString();
			JsonModel.rows = show;
			return this.Json(JsonModel, JsonRequestBehavior.AllowGet);


		}

		public ActionResult ExportCase()
		{
			try
			{
				string folderLevelA = Request["FolderLevelA"];

				string workStatus = Request["WorkStatus"];
				string fileName = Request["FileName"];
				string invoiceNo = Request["InvoiceNo"];
				string receiveDateFrom = Request["ReceiveDateFrom"];
				string receiveDateTo = Request["ReceiveDateTo"];
				string operatorId = Request["OperatorID"];
				string folderLevelB = Request["FolderLevelB"];
				string checkType = Request["CheckType"];
				string queryStatusOperatorId = Request["StatusOperatorID"];
				string statusDateFrom = Request["StatusDateFrom"];
				string statusDateTo = Request["StatusDateTo"];
				string payment = Request["Payment"];
				string reason = Request["Reason"];

				CaseQueryDto caseQueryDto = new CaseQueryDto();
				int d = (int)EnumFolderClass.EEM;
				caseQueryDto.ProcessType = d.ToString();
				caseQueryDto.FolderLevelA = folderLevelA;
				caseQueryDto.FolderLevelB = folderLevelB;
				caseQueryDto.CheckType = checkType;
				caseQueryDto.WorkStatus = workStatus;
				caseQueryDto.FileName = fileName;
				caseQueryDto.InvoiceNo = invoiceNo;
				caseQueryDto.ReceiveDateFrom = receiveDateFrom;
				caseQueryDto.ReceiveDateTo = receiveDateTo;
				caseQueryDto.OperatorId = operatorId;
				caseQueryDto.StatusOperatorID = queryStatusOperatorId;
				caseQueryDto.StatusDateFrom = statusDateFrom;
				caseQueryDto.StatusDateTo = statusDateTo;
				caseQueryDto.Payment = payment;
				caseQueryDto.CommentCode = reason;

				IList<BaseDataReportEEMDto> baseDataReportEEMDtos = CaseEEMService.GetBaseDataReportEEM(caseQueryDto);

				ExportExcel(baseDataReportEEMDtos);

				return Json(new { Success = true, Message = "" }, "text/html", JsonRequestBehavior.AllowGet);

			}
			catch(IndexOutOfRangeException indexOutOfRangeException)
			{
				return Json(new { Success = false, Message = indexOutOfRangeException.Message }, "text/html", JsonRequestBehavior.AllowGet);
		
			}
			catch (Exception ex)
			{
				var debug = ConfigurationManager.AppSettings["DebugFlag"];

				if (debug == "on")
				{
					return Json(new { Success = false, Message = ex.Message }, "text/html", JsonRequestBehavior.AllowGet);

				}
				else
				{
					return Json(new {Success = false, Message = Global.ActiveFalse}, "text/html", JsonRequestBehavior.AllowGet);
				}
			}
			finally
			{
				GC.Collect();

			}
		}

		private void ExportExcel(IList<BaseDataReportEEMDto> cases)
		{
			
			try
			{
				var reportList = cases.Select(x => new
				                                   	{
				                                   		x.CaseNo,
				                                   		x.BatchNo,
				                                   		x.InvoiceNo,
				                                   		x.FileName,
														x.FolderLevelA,
														x.FolderLevelB,
														x.CheckType,
														ReceiveDate = (x.ReceiveDate).ToString("yyyy/MM/dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo),
														WorkStatusNameEEM = x.WORKSTATUS_NAME_EEM,
				                                   		StatusDate=(x.StatusDate).ToString("yyyy/MM/dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo),
														StatusOperator = x.StatusOperator ?? String.Empty,
				                                   		x.StatusComment,
														Operator = x.OperatorID ?? String.Empty,
														PaymentEEM = x.PAYMENT_NAME ?? String.Empty,
														Reason = x.JP_REASON ?? String.Empty
				                                   	});

				DataTable dataTable = ToolsHelper.ToDataTable(reportList.ToList());

				string path = Server.MapPath("~/ReportTemplate/DATA_BASE_EEM.xls");
				string pathTemp = Server.MapPath("~/TempFiles/" + ToolsHelper.GetTimeZoneNow().ToString("yyyyMMddhhmmss") + ".xls");
				ReportForm reportForm = new ReportForm();
				reportForm.IReport.OpenOneSheet(path);
				reportForm.IReport.WorkSheetName = "DATA BASE";
				reportForm.IReport.MaxRowCount = 50000 + 4;
				DrawSheet(dataTable, reportForm.IReport);
				reportForm.IReport.ExportToExcel(pathTemp);
				
				var file = new FileInfo(pathTemp);
				Response.Clear();
				Response.Buffer = true;
				Response.Charset = "";
				Response.AppendHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(ToolsHelper.GetTimeZoneNow().ToString("yyyyMMddhhmmss") + ".xls"));
				//Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文

				Response.WriteFile(file.FullName);
				Response.End();
				System.IO.File.Delete(pathTemp);
			}
			catch (Exception ex)
			{

				throw ex;
			}
			
		}


		private void DrawSheet(System.Data.DataTable dtReport, GCDF.Common.Report.AdapterInterFace.IReport iReport)
		{
			MutiDimensionAndDetailReportDrawer drawer = new MutiDimensionAndDetailReportDrawer(iReport);

			drawer.AddColumn(iReport.GetText(1, 1).ToString(), "CaseNo");
			drawer.AddColumn(iReport.GetText(1, 2).ToString(), "BatchNo");
			drawer.AddColumn(iReport.GetText(1, 3).ToString(), "InvoiceNo");
			drawer.AddColumn(iReport.GetText(1, 4).ToString(), "FileName");
			drawer.AddColumn(iReport.GetText(1, 5).ToString(), "FolderLevelA");
			drawer.AddColumn(iReport.GetText(1, 6).ToString(), "FolderLevelB");
			drawer.AddColumn(iReport.GetText(1, 7).ToString(), "CheckType");
			drawer.AddColumn(iReport.GetText(1, 8).ToString(), "ReceiveDate");
			drawer.AddColumn(iReport.GetText(1, 9).ToString(), "WorkStatusNameEEM");
			drawer.AddColumn(iReport.GetText(1, 10).ToString(), "StatusDate");
			drawer.AddColumn(iReport.GetText(1, 11).ToString(), "StatusOperator");
			drawer.AddColumn(iReport.GetText(1, 12).ToString(), "PaymentEEM");
			drawer.AddColumn(iReport.GetText(1, 13).ToString(), "Reason");
			drawer.AddColumn(iReport.GetText(1, 14).ToString(), "StatusComment");
			drawer.AddColumn(iReport.GetText(1, 15).ToString(), "Operator");

			drawer.FormatDescriptionCollection = FormatDescriptionCollection.CreateDefault();
			drawer.DrawReport(1, 1, dtReport);
			iReport.DrawLine(2, dtReport.Rows.Count,1,15);
		}

	}
}
